package cn.itcast.Rainbow_self_mention.Activity;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import RJZ.Rainbow.UserServer.entity.OrderEntity;
import cn.itcast.Rainbow_self_mention.R;
import cn.itcast.Rainbow_self_mention.Server.OrderServer;
import cn.itcast.Rainbow_self_mention.Dao.SqlHelper;

public class Home extends AppCompatActivity {
    public ImageView home, order, map, mine;
    List<OrderEntity> orderEntities;
    ListView lv;
    Intent server;
    MyServiceConn conn;
    static OrderServer.Sender sender;
    ImageView shou, fa;
    static Boolean link = false;
    int whichlist = 0;
    static int ogain = 5;
    static String sentresult;
    RelativeLayout get, give;
    SqlHelper hp = new SqlHelper(Home.this);
    RelativeLayout connecting;
    RelativeLayout all;
    ImageView loading, imageView, flush;
    private Timer timer_for_connect;
    String username;
    int userid;
    AlertDialog dialog;

    Animation roll;
    adapter ad = new adapter();

    static Boolean delete = false;

    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
    }
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.low_home);

        server = new Intent(Home.this, OrderServer.class);//创建意图对象
        conn = new MyServiceConn();//创建服务连接对象
        bindService(server, conn, BIND_AUTO_CREATE);

        init();
        initbutton();

        connecting = new RelativeLayout(Home.this);
        loading = new ImageView(Home.this);
        roll = AnimationUtils.loadAnimation(Home.this, R.anim.roate_animation);
        SQLiteDatabase db = hp.getReadableDatabase();
        Cursor cursor = db.query("logined", new String[]{"username", "userid"}, "_id=?", new String[]{"1"}, null, null, null);
        cursor.moveToFirst();
        username = cursor.getString(cursor.getColumnIndex("username"));
        userid = cursor.getInt(cursor.getColumnIndex("userid"));
        loading.setBackgroundResource(R.drawable.load);
        cursor.close();
        db.close();
    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent home = new Intent(Intent.ACTION_MAIN);
            home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            home.addCategory(Intent.CATEGORY_HOME);
            startActivity(home);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    public void addTimer() {
        if (timer_for_connect == null) {
            timer_for_connect = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    Looper.prepare();
                    if (link) {
                        switch (ogain) {
                            case 0: {
                                all = new RelativeLayout(Home.this);

                                AlertDialog.Builder builder;
                                TextView t = new TextView(Home.this);
                                t.setText("订单获取失败");
                                t.setTextSize(40);
                                RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                                        , RelativeLayout.LayoutParams.WRAP_CONTENT);
                                params2.addRule(RelativeLayout.CENTER_IN_PARENT);
                                all.addView(t, params2);
                                builder = new AlertDialog.Builder(Home.this).setView(all);
                                dialog = builder.create();
                                dialog.show();
                                break;
                            }
                            case 1: {
                                all = new RelativeLayout(Home.this);

                                AlertDialog.Builder builder;
                                TextView t = new TextView(Home.this);
                                t.setText("正在获取订单");
                                t.setTextSize(40);
                                RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                                        , RelativeLayout.LayoutParams.WRAP_CONTENT);
                                params2.addRule(RelativeLayout.CENTER_IN_PARENT);
                                all.addView(t, params2);
                                builder = new AlertDialog.Builder(Home.this).setView(all);
                                dialog = builder.create();
                                dialog.show();
                                break;
                            }
                            case 2: {
                                if (dialog != null && dialog.isShowing()) {
                                    dialog.dismiss();
                                    onResume();
                                }
                            }
                        }
                    } else {
                        all = new RelativeLayout(Home.this);

                        AlertDialog.Builder builder;
                        TextView t = new TextView(Home.this);
                        t.setText("网络连接失败");
                        t.setTextSize(40);
                        RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT
                                , RelativeLayout.LayoutParams.WRAP_CONTENT);
                        params2.addRule(RelativeLayout.CENTER_IN_PARENT);
                        all.addView(t, params2);
                        builder = new AlertDialog.Builder(Home.this).setView(all);
                        dialog = builder.create();
                        dialog.show();

                    }
                    Looper.loop();
                }
            };
            timer_for_connect.schedule(task, 100, 500);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        work();
    }

    public void work() {


        SQLiteDatabase db = hp.getReadableDatabase();
        Cursor cursor = db.query("chose", null, null, null, null, null, null, null);
        cursor.moveToFirst();
        whichlist = cursor.getInt(cursor.getColumnIndex("which"));
        db.close();
        cursor.close();
        if (whichlist == 0) {
            Drawable d = this.getResources().getDrawable(R.drawable.get2);//此处icon对应drawable文件夹下的icon.png
            shou.setImageDrawable(d);//设置图片
            //shou.setBackground(R.drawable.get2);
            d = this.getResources().getDrawable(R.drawable.send);
            fa.setBackground(d);
            initreceivesql();
        }
        if (whichlist == 1) {
            Drawable d = this.getResources().getDrawable(R.drawable.get);//此处icon对应drawable文件夹下的icon.png
            shou.setImageDrawable(d);//设置图片
            //shou.setBackground(R.drawable.get2);
            d = this.getResources().getDrawable(R.drawable.send2);
            fa.setBackground(d);
            initordersql();
        }
    }


    //删除订单函数
    public void Delete(String number) {
        if (whichlist == 0) {
            sender.rec_delete(number,userid+"");
            if (delete) {
                SQLiteDatabase db = hp.getWritableDatabase();
                db.delete("HISTORY", "NUMBER=?", new String[]{number});
                db.close();
            }

        }
        if (whichlist == 1) {
            sender.sub_delete(number,userid+"");
            if (delete) {
                SQLiteDatabase db = hp.getWritableDatabase();
                db.delete("HISTORY", "NUMBER=?", new String[]{number});
                db.close();
            }
        }

        //lv.setEmptyView(imageView);
        new Swtch().start();
        if (whichlist == 0) {
            initreceivesql();
        }
        if (whichlist == 1) {
            initordersql();
        }


    }

    //加载listview控件
    public void initalllistview() {
        if (orderEntities.size() > 0) {
            ad.SetListview(lv);
            ad.SetOnclicklistener(lv);
            ad.SetOnlongClicklistener(lv);
        }
    }

    //加载寄件订单
    public void initordersql() {

        SQLiteDatabase db;
        db = hp.getReadableDatabase();
        Cursor cursor = db.query("HISTORY", new String[]{"NUMBER", "NAME_OF_PRODUCTION", "TIME_OF_ORDER", "RECEIVE_OR_NOT", "NAME_OF_PICTURE"},
                "NAME_OF_SUBMIT=?", new String[]{username}, null, null, null);
        cursor.moveToFirst();
        orderEntities=new LinkedList<>();
        if (cursor.getCount() > 0) {
            cursor.moveToLast();
            for (int j = 0; j < cursor.getCount(); j++) {
                OrderEntity oe=new OrderEntity(cursor.getString(cursor.getColumnIndex("NAME_OF_PRODUCTION")),
                        cursor.getString(cursor.getColumnIndex("TIME_OF_ORDER")),
                        cursor.getString(cursor.getColumnIndex("NUMBER")),
                        cursor.getString(cursor.getColumnIndex("NAME_OF_PICTURE")),
                        cursor.getInt(cursor.getColumnIndex("RECEIVE_OR_NOT")));
                orderEntities.add(oe);
                cursor.moveToPosition(j);
            }
            db.close();
            cursor.close();
            initalllistview();
        } else {
            lv.setEmptyView(imageView);
        }

    }

    //加载取件订单
    public void initreceivesql() {
        SQLiteDatabase db;
        db = hp.getReadableDatabase();
        Cursor cursor = db.query("HISTORY", new String[]{"NUMBER", "NAME_OF_PRODUCTION", "TIME_OF_ORDER", "RECEIVE_OR_NOT", "NAME_OF_PICTURE"},
                " NAME_OF_RECEIVER=?", new String[]{username}, null, null, null);
        cursor.moveToFirst();
        orderEntities=new LinkedList<>();
        if (cursor.getCount() > 0) {
            cursor.moveToLast();
            for (int j = 0; j < cursor.getCount(); j++) {
                OrderEntity oe=new OrderEntity(cursor.getString(cursor.getColumnIndex("NAME_OF_PRODUCTION")),
                        cursor.getString(cursor.getColumnIndex("TIME_OF_ORDER")),
                        cursor.getString(cursor.getColumnIndex("NUMBER")),
                        cursor.getString(cursor.getColumnIndex("NAME_OF_PICTURE")),
                        cursor.getInt(cursor.getColumnIndex("RECEIVE_OR_NOT")));
                orderEntities.add(oe);
                cursor.moveToPosition(j);
            }
            db.close();
            cursor.close();
            initalllistview();
        } else {

            lv.setEmptyView(imageView);

        }

    }

    class Swtch extends Thread {
        @Override
        public void run() {
            threadwait(2);
            Looper.prepare();
            if (delete) {
                Toast.makeText(Home.this, "订单删除成功", Toast.LENGTH_SHORT).show();


            } else {
                Toast.makeText(Home.this, "订单删除失败", Toast.LENGTH_SHORT).show();
            }
            Looper.loop();
        }
    }

    class adapter extends BaseAdapter {
        public ViewHolder holder;
        public boolean longpoint = false;

        public void SetOnlongClicklistener(ListView lv) {
            lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                @Override
                public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
                    longpoint = true;
                    AlertDialog dialog;
                    AlertDialog.Builder builder = new AlertDialog.Builder(Home.this).setMessage("是否删除该订单?")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Delete(orderEntities.get(position).getNUMBER());
                                    dialog.dismiss();
                                    longpoint = false;
                                    notifyDataSetChanged();
                                    Toast.makeText(Home.this, "删除成功！", Toast.LENGTH_SHORT).show();

                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    notifyDataSetChanged();
                                    longpoint = false;
                                    Toast.makeText(Home.this, "订单没有删除！", Toast.LENGTH_SHORT).show();
                                }
                            });
                    dialog = builder.create();
                    dialog.show();

                    return false;
                }
            });
        }

        public void SetOnclicklistener(ListView lv) {
            lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (!longpoint) {
                        Intent intent;

                        if (whichlist == 0) {
                            if (orderEntities.get(position).getTakeornot() == 3) {
                                intent = new Intent();
                                intent.setClass(Home.this, History.class);
                                intent.putExtra("number", orderEntities.get(position).getNUMBER());
                                startActivity(intent);
                            } else if (orderEntities.get(position).getTakeornot() == 2) {
                                intent = new Intent();
                                intent.setClass(Home.this, Detail_for_rec.class);
                                intent.putExtra("number", orderEntities.get(position).getNUMBER());
                                startActivity(intent);
                            } else if (orderEntities.get(position).getTakeornot() == 1) {
                                intent = new Intent();
                                intent.setClass(Home.this, History.class);
                                intent.putExtra("number", orderEntities.get(position).getNUMBER());
                                startActivity(intent);
                            }
                        } else {
                            if (orderEntities.get(position).getTakeornot() == 3) {
                                intent = new Intent();
                                intent.setClass(Home.this, History.class);
                                intent.putExtra("number", orderEntities.get(position).getNUMBER());
                                startActivity(intent);
                            } else if (orderEntities.get(position).getTakeornot() == 2) {
                                intent = new Intent();
                                intent.setClass(Home.this, Detail_for_sub.class);
                                intent.putExtra("number", orderEntities.get(position).getNUMBER());
                                startActivity(intent);

                            } else if (orderEntities.get(position).getTakeornot() == 1) {
                                intent = new Intent();
                                intent.setClass(Home.this, Detail_for_sub.class);
                                intent.putExtra("number", orderEntities.get(position).getNUMBER());
                                startActivity(intent);
                            }
                        }
                    }
                }
            });
        }

        public void SetListview(ListView lv) {
            lv.setAdapter(this);
        }

        @Override
        public int getCount() {
            return orderEntities.size();
        }

        public Object getItem(int position) {
            return orderEntities.get(position).getName();
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = View.inflate(Home.this, R.layout.activity_foot_item, null);
                holder = new ViewHolder();
                holder.name_of_good = (TextView) convertView.findViewById(R.id.footitem_content);
                holder.time_of_order = (TextView) convertView.findViewById(R.id.footitem_puttime);
                holder.picture = (ImageView) convertView.findViewById(R.id.picture);
                holder.take_or_not = (ImageView) convertView.findViewById(R.id.take_or_not);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.name_of_good.setText(orderEntities.get(position).getName());
            holder.time_of_order.setText(orderEntities.get(position).getTime());
            holder.number_of_order = orderEntities.get(position).getNUMBER();
            holder.Wtake = orderEntities.get(position).getTakeornot();
            if (holder.Wtake != 3) {
                holder.take_or_not.setBackgroundResource(R.drawable.yes);
            } else if (holder.Wtake != 2) {
                holder.take_or_not.setBackgroundResource(R.drawable.yes);
            } else if (holder.Wtake != 1) {
                holder.take_or_not.setBackgroundResource(R.drawable.yes);
            }
            return convertView;
        }
    }

    static class ViewHolder {
        ImageView picture, take_or_not;
        TextView name_of_good;
        TextView time_of_order;
        String number_of_order;
        int Wtake;
    }
    @Override
    public void onBackPressed() {
        Intent MyIntent = new Intent(Intent.ACTION_MAIN);
        MyIntent.addCategory(Intent.CATEGORY_HOME);
        startActivity(MyIntent);
    }
    public void threadwait(int time) {
        try {
            Thread.sleep(time * 500);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public void init() {
        home = findViewById(R.id.foot_homepage);
        order = findViewById(R.id.foot_deposit);
        map = findViewById(R.id.foot_map);
        mine = findViewById(R.id.foot_my);
        lv = findViewById(R.id.listview);
        get = findViewById(R.id.shou);
        give = findViewById(R.id.fa);
        shou = findViewById(R.id.get);
        fa = findViewById(R.id.give);
        imageView = findViewById(R.id.kong);
        lv.setEmptyView(imageView);
        flush = findViewById(R.id.flush);
    }

    class MyServiceConn implements ServiceConnection { //用于实现连接服务
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            sender = (OrderServer.Sender) service;
            sender.gain_send(userid);
            sender.gain_received(userid);
            onResume();
            addTimer();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    }


    public void initbutton() {
        flush.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (link) {
                    sender.gain_send(userid);
                    sender.gain_received(userid);
                }
                onResume();
            }
        });
        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onResume();
            }
        });
        order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Home.this, Order.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
                //finish();
            }
        });
        map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Home.this, Map.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
                //finish();
            }
        });
        mine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Home.this, Personal.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
                //finish();
            }
        });
        get.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = hp.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("which", 0);
                db.update("chose", values, "_id=?", new String[]{"1"});
                db.close();
                if (link) {
                    sender.gain_send(userid);
                    sender.gain_received(userid);
                }
                onResume();
            }
        });
        give.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SQLiteDatabase db = hp.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put("which", 1);
                db.update("chose", values, "_id=?", new String[]{"1"});
                db.close();
                if (link) {
                    sender.gain_send(userid);
                    sender.gain_received(userid);

                }
                onResume();
            }
        });

    }

    /*public void initfile() {
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        String dirName = "WMZTG";
        File appDir = new File(root, dirName);
        if (!appDir.exists()) {
            appDir.mkdirs();
        }
        file = appDir.getPath();

    }*/

    public static Handler handler = new Handler() {//创建消息处理器对象
        //在主线程中处理从子线程发送过来的消息
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            sentresult = bundle.getString("sentresult");
            if (sentresult.equals("网络连接错误")) {
                link = false;
            }
            if (sentresult.equals("网络连接成功")) {
                link = true;
            }
            if (sentresult.equals("获取订单失败")) {
                ogain = 0;
            }
            if (sentresult.equals("当前正在获取订单")) {
                ogain = 1;
            }
            if (sentresult.equals("订单全部获取")) {
                ogain = 2;
            }
            if (sentresult.equals("取件删除失败")) {
                delete = false;
            }
            if (sentresult.equals("取件删除成功")) {
                delete = true;
            }
            if (sentresult.equals("投件删除失败")) {
                delete = false;
            }
            if (sentresult.equals("投件删除成功")) {
                delete = true;
            }

        }
    };
}
